package server.model.userModel;

import org.apache.commons.dbutils.handlers.BeanHandler;
import server.db.DBDriver;
import server.db.DBFactory;
import server.entity.Code;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoEnum;
import server.util.InfoUtils.InfoUtil;
import server.util.JWTUtils;

public class TokenModel {
    public int setToken(Integer userId, String token) {
        String sql = "update code set token = ? where user_id = ? limit 1";
        int line = DBFactory.getDBDriver().update(sql, token, userId);
        return line;
    }

    /**
     * 判断token是否存在
     * @param token
     * @return token对应的userId
     */
    public Integer judgeToken(String token) {
        String sql = "select user_id from code where token = ?  limit 1";
        Code code = DBFactory.getDBDriver().query(sql, new BeanHandler<>(Code.class, DBDriver.getProcess()), token);
        if(code==null) return null;
        return code.getUserId();
    }

    /**
     * 原有token已过期，设置refreshToken
     * @param userId
     * @param token
     * @return refreshToken info
     */
    public Info refreshToken(Integer userId, String token) {
        Info info=null;
        String sql = "update code set token = ? where token = ?  limit 1";
        String refreshToken = JWTUtils.sign(userId);

        int line = DBFactory.getDBDriver().update(sql,refreshToken, token);
        if(line>0){
            info= InfoUtil.getInfo(2,"原有token已过期",refreshToken);
        }else {
            info=InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return info;
    }
}
